var cusFlag=0;
var cusUnique;//用户唯一性标识
var shopUnique;//店铺唯一性标识
var cusAccount;//用户帐号-保留
var shopLongitude=0;//店铺经度
var shopLatitude=0;//店铺纬度
var EARTH_RADIUS = 6378.137;// 地球半径;单位米;6378.137千米

var imgUrl="http://121.42.189.191:80/";//全局变量-服务器地址

$(document).ready(function() {
	$("#shopMain").css("display","none");//隐藏加载图片
	$("#imgLoading2").show();//显示店铺信息页面
	
	var  cusId = getCookie("cusId");//用户登录后会存储cusId到cookie
	var  cusUniqueF=getCookie("cusUnique");
	if (cusId!= null) {// 判断用户是否登录状态；如果是则显示用户的相关信息-头像-登录名-购物车信息等
		cusUnique=cusId;
		
	}else if(cusUniqueF!=null){
		cusUnique=cusUniqueF;
		cusFlag=1;
	}else{
		cusUnique=new Date().getTime();
		cusFlag=1;
	} 
	
	addCookie("cusUnique",cusUnique,100);//保存100小时
	//getLocationIP();//获取当前坐标
	
	var shopUniqueB=getCookie("shopUnique");//判断之前是否有登录过的店铺
	
	if(shopUniqueB==null){
		getLatitude();//百度API定位
	}else{
		$("#imgLoading2").css("display","none");//隐藏加载图片
		$("#shopMain").show();//显示店铺信息页面
		
		shopUnique=shopUniqueB;
		searchGoods(shopUnique, "none", "none");//加载商品
		sumBasket(shopUnique);//加载购物车信息 
		shopInfo(shopUnique);//加载店铺基本信息
	}
	
	
	
});

//根据店铺标识获取店铺基本信息ok
function shopInfo(shopUnique){
	$.ajax({
		url : "../online/findShopInfo.do",
		type : "post",
		data : {
			"shopUnique":shopUnique
		},
		dataType : "json",
		success : function(result) {
			if (result.status == 1) {// 查询成功
				$("#shopinfos").text(result.data.shopAddressDetail+":"+result.data.shopName);//商铺名称
			} else {
				
			}
		},
		error : function(XMLHttpRequest, textStatus, errorThrown) {

		}
	});
}


/**
 * 根据用户唯一性标识和店铺唯一性标识
 * 动态查询用户购物车中的商品数量
 */
function sumBasket(shopUnique) {
	$.ajax({
		url : "../basket/findSumBasket.do",
		type : "post",
		data : {
			"cusId" : cusUnique,"shopUnique":shopUnique
		},
		dataType : "json",
		success : function(result) {
			
			if (result.status == 1) {// 查询成功
				$("#shopcart-number").text(result.data);
			} else {
				$("#shopcart-number").text(0);
			}
		},
		error : function(XMLHttpRequest, textStatus, errorThrown) {

		}
	});

}

//获取当前坐标 百度API
function getLatitude() {
	// 默认地理位置设置为上海市浦东新区
	var x = 121.48789949, y = 31.24916171;
	if (navigator.geolocation) {
		navigator.geolocation.getCurrentPosition(showPosition);
		document.getElementById("status").innerHTML = "HTML5 Geolocation is supported in your browser.";
		// 百度地图API功能
		var map = new BMap.Map("container");
		var point = new BMap.Point(x, y);
		map.centerAndZoom(point, 12);
		var geolocation = new BMap.Geolocation();
		geolocation.getCurrentPosition(function(r) {
			if (this.getStatus() == BMAP_STATUS_SUCCESS) {
				var mk = new BMap.Marker(r.point);
				map.addOverlay(mk);
				map.panTo(r.point);
				console.log(r.point);
				console.log(r.point.lat+";"+r.point.lng);
				shopLongitude=r.point.lng;
			    shopLatitude=r.point.lat;
			    initialShop();// 加载店铺信息
				
			} else {
				alert('获取您的位置信息失败');
			}
		}, {
			enableHighAccuracy : true
		})
		return;
	}
	alert("你的浏览器不支持获取地理位置！");
}



//根据用户ip获取用户的地理位置
function getLocationIP() {
	$.ajax({
		url : "../cus/getLocation.do",
		type : "post",
		data : {},
		dataType : "json",
		success : function(result) {
			if (result.status == 1) {// 查询成功
				// alert("您当前的位置是:"+result.data[0]+";"+result.data[1]);
				console.log(result.data[0] + ";" + result.data[1]);
				shopLongitude=result.data[0];
			    shopLatitude=result.data[1];
				initialShop();// 加载店铺信息

			} else {// 查询不到的话做出相应的提示信息
				// 手动选择当前位置
			}
		},
		error : function(XMLHttpRequest, textStatus, errorThrown) {
		}
	});
}

//h5定位当前位置并获取最近的商铺信息
var x=document.getElementById("demo");
function getLocation() {
	
	if (navigator.geolocation) {
		navigator.geolocation.getCurrentPosition(showPosition);
	} else {
		x.innerHTML = "Geolocation is not supported by this browser.";
	}
}
function showPosition(position) {
	console.log("Latitude: " + position.coords.latitude + "Longitude: "
			+ position.coords.longitude);
	
	shopLongitude=position.coords.longitude;
    shopLatitude=position.coords.latitude;
	initialShop();// 加载店铺信息
}

//初始化加载商铺信息
function initialShop() {
	$("#imgLoading2").css("display","none");//隐藏加载图片
	$("#shopMain").show();//显示店铺信息页面
	
	var tradeAreaUnique = "永恒华府";// 测试数据用--
	$
			.ajax({
				url : "../online/findShopByLocation.do",
				type : "post",
				data : {
					"tradeAreaUnique" : tradeAreaUnique,
					"shopLongitude":shopLongitude,
					"shopLatitude":shopLatitude
				},
				dataType : "json",
				success : function(result) {
					console.log(result);
					if (result.status == 1) {// 查询成功
						$("#shop-shopsinfo").show();
						shopUnique=result.data.shopUnique;
						$("#shopinfos").text(result.data.shopAddressDetail+":"+result.data.shopName);//商铺名称
						addCookie("shopUnique",shopUnique,0);//店铺唯一性标识保存
						searchGoods(shopUnique, "none", "none");//加载商品
						sumBasket(shopUnique);//加载购物车信息 
					} else {// 查询不到的话做出相应的提示信息

					}
				},
				error : function(XMLHttpRequest, textStatus, errorThrown) {

				}
			});

}

//跳转购物车页面
function goShopcar(){
	window.location.href="shopcar.html?cusUnique="+cusUnique+"&shopUnique="+shopUnique;
}

//搜索框查询商品信息
function serchGoods(){
	var searchBar=$("#searchBox").val().trim().toUpperCase();
	
	searchGoods(shopUnique, searchBar, "none");
}





//选择店铺后加载商品信息
function initial(shopUnique,searchBar,goodsKind) {
	$
			.ajax({
				url : "../online/findByCondition.do",
				type : "post",
				data : {
					"shopUnique" : shopUnique
				},
				dataType : "json",
				success : function(result) {
					if (result.status == 1) {// 查询成功
						
						$("#shop-goods").empty();
						var data = result.data;
						var goods = "";
						for (var a = 0; a < data.length; a++) {
							var good = "";
							good+='<div class="list clearfloat fl">'+
			        			      '<a href="detail.html?goodsId='+data[a].goods_id+'&cusFlag='+cusFlag+'">'+
		        			          '<div class="tu clearfloat">'+
		        				      '<img src="upload/9.jpg"/>'+
		        			          '</div>'+
		        			     '<div class="bottom clearfloat box-s">'+
		        				     '<p class="over">'+data[a].goods_name+'</p>'+
		        				  '<span>¥'+data[a].goods_sale_price+'</span>'+
		        			     '</div>'+
	        			         '</a>'+
	        		             '</div>';
							
							goods += good;
						}
						$("#shop-goods").append(goods);
						
						
						
						
					} else {
						$('#alert-error').text('商品正在上架，稍后！');
						$('#alert-error').slideToggle(300);
						setTimeout(function(){$('#alert-error').slideUp(200);}, 1000);
						return;
					}
				},
				error : function(XMLHttpRequest, textStatus, errorThrown) {

				}
			});

}




//手动查询商品信息
function searchGoods(shopUnique, searchBar, goodsKind) {
	console.log("shopUnique:"+shopUnique+";searchBar:"+searchBar+";goodsKind:"+goodsKind)
	var totals = 10;
	if (shopUnique == null) {
		window.location.href = "index.html";
	}
	
	$
			.ajax({
				url : "../online/findGoodsBySearch.do",
				type : "post",
				data : {
					"goodsName" : searchBar,
					"shopUnique" : shopUnique,
					"goodsKind" : goodsKind,
					"pages" : 0,
					"perpage" : 60
				},
				dataType : "json",
				success : function(result) {
					console.log(result);
					console.log("ceil:"+Math.floor(1.2));
				
					if (result.status == 1) {// 查询成功
						$('#pageGoods').show();
						totals=result.totals;
						console.log("page:"+Math.floor((totals-1)/20)+1);
						$("#shop-goods").empty();
						var data = result.data;
						var goods = "";
						for (var a = 0; a < data.length; a++) {
							var good = "";
							good+='<div class="list clearfloat fl">'+
			        			      '<a href="detail.html?goodsId='+data[a].goods_id+'&cusFlag='+cusFlag+'">'+
		        			          '<div class="tu clearfloat">'+
		        				      '<img src="'+imgUrl+data[a].goods_picturepath+'"/>'+
		        			          
//		        			          '<img src="http://121.42.189.191:8080/imageGoods/no_goods.jpg"/>'+
		        			          
		        			          '</div>'+
		        			     '<div class="bottom clearfloat box-s">'+
		        				     '<p class="over">'+data[a].goods_name+'</p>'+
		        				  '<span>¥'+data[a].goods_sale_price+'</span>'+
		        			     '</div>'+
	        			         '</a>'+
	        		             '</div>';
							
							goods += good;
						}
						$("#shop-goods").append(goods);
						$('#pageGoods').jqPagination({
							link_string: '/?page={page_number}',
							current_page: 1, //设置当前页 默认为1
							max_page: Math.floor((totals-1)/20)+1, //设置最大页 默认为1
							page_string: '第{current_page}页,共{max_page}页',
							paged: function(page) {
								$
								.ajax({
									url : "../online/findGoodsBySearch.do",
									type : "post",
									data : {
										"goodsName" : searchBar,
										"shopUnique" : shopUnique,
										"goodsKind" : goodsKind,
										"pages" : page,
										"perpage" : 20
									},
									dataType : "json",
									success : function(result) {
										if (result.status == 1) {// 查询成功
											$("#shop-goods").empty();
											var data = result.data;
											var goods = "";
											for (var a = 0; a < data.length; a++) {
												var good = "";
												
												good+='<div class="list clearfloat fl">'+
								        			      '<a href="detail.html?goodsId='+data[a].goods_id+'&cusFlag='+cusFlag+'">'+
							        			          '<div class="tu clearfloat">'+
							        			          '<img src="'+imgUrl+data[a].goods_picturepath+'"/>'+
							        			          '</div>'+
							        			     '<div class="bottom clearfloat box-s">'+
							        				     '<p class="over">'+data[a].goods_name+'</p>'+
							        				  '<span>¥'+data[a].goods_sale_price+'</span>'+
							        			     '</div>'+
						        			         '</a>'+
						        		             '</div>';
												
												goods += good;
											}
											$("#shop-goods").append(goods);
										} else {
											$("#shop-goods").empty();
											var good="";
											good = '<div class="list clearfloat fl">' + '<a href="#">'
											+ '<div class="tu clearfloat">'
											+ '<img src="upload/hot.jpg" />' + '</div>'
											+ '<div class="bottom clearfloat box-s">'
											+ '<p class="over">看看其他商品吧</p>' + '<span></span>'
											+ '</div>' + '</a>' + '</div>';
											
											$("#shop-goods").append(good);
										}
									},
									error : function(XMLHttpRequest, textStatus, errorThrown) {

									}
								});
								
							}
						});//jqPagination-------end
						
						
					} else {
						
						$("#shop-goods").empty();
						var good="";
						good = '<div class="list clearfloat fl">' + '<a href="#">'
						+ '<div class="tu clearfloat">'
						+ '<img src="upload/hot.jpg" />' + '</div>'
						+ '<div class="bottom clearfloat box-s">'
						+ '<p class="over">看看其他商品吧</p>' + '<span></span>'
						+ '</div>' + '</a>' + '</div>';
						
						$("#shop-goods").append(good);
						
						$('#pageGoods').css("display","none");
						
					}
				},
				error : function(XMLHttpRequest, textStatus, errorThrown) {

				}
			});

}




//去商品列表页面
function goList(){
	if(shopUnique!=null){
		window.location.href="list.html?cusUnique="+cusUnique+"&shopUnique="+shopUnique+"&cusFlag="+cusFlag;
	}
}

















